Skip to main content

Validation

This article will show you how to create a Validate decorator.

We will use fastest-validator-decorators and class-transformer. If you want, it is very simple to use another validation library.

First, let install these packages.

yarn add fastest-validator-decoratorsyarn add class-transformer

Next, we will create Validate decorator with the help of DI Proxy.

// validate.deco.tsimport { Schema, validate } from 'fastest-validator-decorators';import { plainToInstance } from 'class-transformer';import { addProxy, ProxyHandler, ProxyContext, Injectable } from '@cellularjs/di';
class ValidateProxy implements ProxyHandler {  constructor(    private irq: IRQ,    private ctx: ProxyContext,  ) {}
  async handle() {    const { irq, ctx } = this;    const dto = plainToInstance(ctx.token, irq.body);
    const errors = await validate(dto);
    if (errors !== true) {      ctx.meta.onError(errors);      return;    }
    return dto;  }}
export const Validate = () => aClass => {  const onError = errors => {    throw new IRS({ status: 400 }, { errors });  }
  addProxy(aClass, { proxy: ValidateProxy, meta: { onError } });
  // fastest-validator-decorators  Schema({ strict: true })(aClass);
  // allow to detect this class as a provider while scanning  Injectable()(aClass);
  return aClass;};

Now you can use Validate decorator everywhere.

// sign-in.req.tsimport { String } from 'fastest-validator-decorators';import { Validate } from './validate.deco';
@Validate()export class SignInReq {  @String({ length: 8 })  usr: string;
  @String({ length: 8 })  pwd: string;}
import { Service, ServiceHandler } from '@cellularjs/net';import { SignInReq } from './sign-in.req';
@Service({ scope: 'publish' })export class SignIn implements ServiceHandler {  constructor(    private signInReq: SignInReq,  ) { }
  handle() {    // ...  }}